<template>
   <el-dialog v-model="dialogTableVisible" :title="title" @close="handleClear">
     <div style="max-height:60vh;overflow:auto;">
       <el-form :model="formData" ref="formRef" label-width="100px">
         <el-form-item label="图标" prop="icon" :rules="[{required: true,message: '请上传图标',trigger: 'blur'}]">
           <uploadimg dir="classify_icon" v-model="formData.icon"/>
         </el-form-item>
         <el-form-item label="父级分类" prop="pid" :rules="[{required: true,message: '请选择父级分类',trigger: 'blur',type:'number'}]">
           <el-cascader v-model="pids" :options="classifyTreeList" :props="{checkStrictly: true,value:'id',label:'name'}" placeholder="请选择父级分类" @change="pidChange"/>
         </el-form-item>
         <el-form-item label="分类名" prop="name" :rules="[{required: true,message: '请输入分类名',trigger: 'blur'}]">
           <el-input v-model="formData.name" placeholder="请输入分类名"/>
         </el-form-item>
         <el-form-item label="排序值" prop="sort" :rules="[{required: true,message: '请输入排序值',trigger: 'blur'}]">
           <el-input-number v-model="formData.sort" />
         </el-form-item>
         <el-form-item label="状态" prop="status" :rules="[{required: true,message: '请选择状态',trigger: 'blur',type:'number'}]">
           <el-switch v-model="formData.status" :active-value="1" :inactive-value="0" />
         </el-form-item>
         <el-form-item label="描述">
           <el-input v-model="formData.desc" type="textarea" :rows="2" placeholder="请输入描述"/>
         </el-form-item>       
       </el-form>
     </div>
     <template #footer>
       <el-button @click="handleClear">取消</el-button>
       <el-button type="primary" @click="handleSubmit(formRef)" :loading="loading">提交</el-button>
     </template>
   </el-dialog>
</template>



<script setup lang="ts">
import {ref,unref} from 'vue'
import { ElForm, ElNotification } from 'element-plus'
import { list as listApi,add,edit,detail } from '/@/api/classify'
import uploadimg from '/@/components/uploadimg/index.vue'
import {classify,formData as formDataType} from '../../type'

const formRef = ref()
const title = ref('')
const dialogTableVisible = ref(false)
const loading = ref(false)
const formData = ref<formDataType>({
  desc: '',
  icon: '',
  name: '',
  pid: 0,
  sort: 0,
  status: 1
})
let classifyList:classify[] = []
const classifyTreeList = ref<classify[]>([])
const pids = ref<number[]>([])
const emit = defineEmits(['success'])
let formId = 0

const getPidValue = (arr:number[],list:classify[],pid:number) => {
  for(let i of list){
      if(i.id === pid){
          arr.unshift(i.id);
          getPidValue(arr,list,i.pid);
      }
  }
}

const doTree = (arr:classify[],list:classify[],pid:number) => {
  for(let i of list){
    if(i.pid === pid){
      i.children = []
      arr.push(i)
      doTree(i.children,list,i.id)
    }
  }
}

const getClassifyList = async () => {
  const {data} = await listApi()
  classifyList = data
  const list:classify[] = []
  data.unshift({
    createTime: 0,
    desc: '',
    icon: '',
    id: 0,
    name: '顶级分类',
    pid: -1,
    sort: 0,
    status: 1,
    updateTime: 0
  })
  doTree(list,data,-1)
  classifyTreeList.value = list
}

const pidChange = (ids:number[]) => {
  formData.value.pid = ids[ids.length-1]
}

const handleClear = () => {
   pids.value = []
   formRef.value.resetFields()
   dialogTableVisible.value = false
}

const handleAdd = async () => {
  formId = 0
  title.value = '添加'
  await getClassifyList()
  dialogTableVisible.value = true
}

const handleEdit = async (id:number) => {
   const {data} = await detail(id)
   const arr:number[] = []
   formId = id
   formData.value = data
   title.value = '编辑'
   await getClassifyList()
   getPidValue(arr,classifyList,data.pid)
   pids.value = arr
   dialogTableVisible.value = true
}

const handleSubmit = (formEl: InstanceType<typeof ElForm> | undefined) => {
   if (!formEl) return
   formEl.validate(async (valid) => {
   if (valid) {
      loading.value = true
      try{
         const req = unref(formData)
         if(formId>0){
          await edit(formId,req)
         }else{
          await add(req)
         }
         
         ElNotification({
            type: 'success',
            message: '提交成功'
         })
         handleClear()
         emit('success')
      }finally{
         loading.value = false  
      }     
    }
  })
}

defineExpose({
  handleAdd,
  handleEdit
})
</script>

<style scoped lang="scss">

</style>